package com.cy.thread.生产者和消费者模型;

import cn.hutool.core.thread.ThreadUtil;

import java.util.Random;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;

public class Test {

    private static volatile boolean isStop = false;

    static class Producer implements Runnable {

        private final BlockingQueue<Integer> queue;

        public Producer(BlockingQueue<Integer> queue) {
            this.queue = queue;
        }

        @Override
        public void run() {
            Random random = new Random();
            while (!isStop) {
                try {
                    Thread.sleep(20);
                    queue.put(random.nextInt());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    static class Consumer implements Runnable {

        private final BlockingQueue<Integer> queue;

        public Consumer(BlockingQueue<Integer> queue) {
            this.queue = queue;
        }

        @Override
        public void run() {
            while (true) {
                try {
                    Integer take = queue.take();
                    System.out.println(take);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
        BlockingQueue<Integer> blockingQueue = new LinkedBlockingDeque<>();

        Thread producer1 = new Thread(new Producer(blockingQueue));
        Thread consumer1 = new Thread(new Consumer(blockingQueue));
        Thread consumer2 = new Thread(new Consumer(blockingQueue));
        producer1.start();
        consumer1.start();
        consumer2.start();

        ThreadUtil.sleep(10 * 1000);
        isStop = true;

    }
}
